package dkbta.util.plan.subperunit;

import static java.lang.Math.min;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;

import org.w3c.dom.Element;

import dkbta.util.Pair;
import dkbta.util.data.StatInfo;
import dkbta.util.plan.AbstractPlanMaker;

public class SubPerUnitPlanMaker extends AbstractPlanMaker{
	
	public SubPerUnitPlanMaker(Element plan) {
		super(plan);
	}
	
	public void makePlans(String taskFileName, int numOfUnits){
		FileOutputStream [] fouts = new FileOutputStream[numOfUnits];
		ArrayList<StatInfo> statsInfo = TaskParserUtil.setUnitIDs(super.getStats(), numOfUnits);	 
		 
		 try{
			    FileInputStream fstream = new FileInputStream(taskFileName);
			    DataInputStream in = new DataInputStream(fstream);
			    BufferedReader br = new BufferedReader(new InputStreamReader(in));
			    String strLine;
			    String [] stringOfIntervals = null;
			    String oldInterval = null;
			    String temp = null;
			    String unitString = null;
			    int unitIndx = 0;
			    
			    for(int i = 0; i < numOfUnits; i++){
			    	fouts[i] = new FileOutputStream("Plan-" + (i+1) + ".xml");
			    }
			    
			    boolean isIntervals = false;
			    
			    while ((strLine = br.readLine()) != null)   {
			    	
			    	if(strLine.indexOf("<Stat name")>=0){
			    		break;
			    	}
			    	
			    	if(strLine.indexOf("</Patients>")>=0 && unitIndx>0){
			    		new PrintStream(fouts[unitIndx-1]).println (unitString);
			    		unitIndx = 0;
			    	}
			    	
			    	if(strLine.indexOf("id=")>=0 && strLine.indexOf("Unit")<0)//abstraction
			    	{
			    		
			    		oldInterval = strLine.substring(strLine.indexOf("id=")+4, strLine.length() - 2);
			    		
			    		Pair<Integer, Integer>[] ids = TaskParserUtil.parsePatientIds(oldInterval);
						int numOfPatients = TaskParserUtil.getNumOfPatients(ids);
						stringOfIntervals = TaskParserUtil.parseIntervals(ids, numOfPatients, min(numOfPatients,numOfUnits));
			    		isIntervals = true;
			    	}
			    	
			    	if(strLine.indexOf("name=")>=0 && strLine.indexOf("inputTableName")<0){
			    		String abstrFrom = TaskParserUtil.getAbstractionNameFromString(strLine);
			    		unitIndx = TaskParserUtil.getUnitIDindxForAbstraction(abstrFrom, statsInfo);
			    		for(int i = 0; i < numOfUnits; i++){
			    			if(i==unitIndx-1){
			    				temp = strLine;
			    				unitString = TaskParserUtil.getRemoteCalcString(stringOfIntervals[i], TaskParserUtil.getStatInterval(abstrFrom, statsInfo), temp);
			    			}
			    			else{
			    				temp = strLine.substring(0, strLine.lastIndexOf('"')+1) + " sendToUnits=" + '"' + unitIndx + '"' + 
			    							strLine.substring(strLine.lastIndexOf('"')+1);
			    			}
			    			new PrintStream(fouts[i]).println (temp);
			    		}
			    	}
			    	else
			    	{
			    	
					    	for(int i = 0; i < numOfUnits; i++){
					    		if(isIntervals){
					    			temp = strLine.replaceFirst(oldInterval, stringOfIntervals[i]);
					    			new PrintStream(fouts[i]).println (temp);
					    		}
					    		else{
					    			new PrintStream(fouts[i]).println (strLine);
					    		}
					    	}
					    	isIntervals = false;
			    	}
			    }
			    
			    for(int i = 0; i < statsInfo.size(); i++){
			    	StatInfo stat = statsInfo.get(i);
			    	int indx = stat.getUnitID() - 1;
			    	new PrintStream(fouts[indx]).println (stat.toString());
			    }
			    			    
			    for(int i = 0; i < numOfUnits; i++){
			    	new PrintStream(fouts[i]).println ("\t</Statistical>");
			    	new PrintStream(fouts[i]).println ("</Plan>");
			    	fouts[i].close();
			    }
			    in.close();
			    }catch (Exception e){
			      System.err.println("Error: " + e.getMessage());
			    }
	}

}
